package org.wlw.user;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class UserManager {
	public final static String PATH = "c:/user.save";
	private List<User> users;
	
	public UserManager() {
		//此处应该从文件中进行读取
		//如果第一次文件不存在，就应该执行new来创建文件
		load();
	}
	
	public void load() {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(PATH));
			users = (List<User>)ois.readObject();
		} catch (FileNotFoundException e) {
			//表示第一次执行
			System.out.println("存储文件准备完成");
			users = new ArrayList<User>(); 
			File f = new File(PATH);
			try {
				f.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void save() {
		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new FileOutputStream(PATH));
			oos.writeObject(users);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(oos!=null) oos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public User load(String username) {
		for(User u:users) {
			if(username.equals(u.getUsername())) 
				return u;
		}
		return null;
	}
	
	public void list() {
		System.out.println("\t用户名\t\t用户昵称\t\t年龄\t\t密码");
		System.out.println("**********************************************************************************");
		for(User u:users) {
			System.out.println(u);
		}
	}
	
	public void add(int pos,User user) {
		if(user.getPassword().length()<=2) {
			throw new UserException("密码太短!");
		}
		User tu = load(user.getUsername());
		if(tu!=null) {
			throw new UserException("用户名已经存在！不能添加");
		}
		users.add(pos, user);
		save();
	}
	
	public void add(User user) {
		add(users.size(),user);
	}
	
	public void delete(String username) {
		User tu = load(username);
		if(tu==null) {
			throw new UserException("删除的用户不存在!");
		}
		users.remove(tu);
		save();
	}
	
	public void update(User user) {
		User tu = this.load(user.getUsername());
		if(tu==null) {
			throw new UserException("更新的用户不存在!");
		}
		tu.setAge(user.getAge());
		tu.setNickname(user.getNickname());
		tu.setPassword(user.getPassword());
		save();
	}
	
	public User login(String username,String password) {
		User tu = this.load(username);
		if(tu==null) {
			throw new UserException("用户不存在！");
		}
		if(!tu.getPassword().equals(password)) {
			throw new UserException("密码不正确!");
		}
		return tu;
	}
}
